<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Base\ServerList;
use App\Models\Base\StatEverdayPlayer;
use App\Service\AccountService;
use App\Service\OrderService;
use App\Service\PayService;
use App\Service\PlayerService;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Table;

class HomeController extends Controller {
	protected $playService;

	protected $pay;

	protected $amount;

	/**
	 * [$yesterday 昨天日期].
	 *
	 * @var [type]
	 */
	protected $yesterday;

	/**
	 * [$yesterdayTimestamp 昨天时间戳].
	 *
	 * @var [type]
	 */
	protected $yesterdayTimestamp;

	/**
	 * [$today 今天日期].
	 *
	 * @var [type]
	 */
	protected $today;

	/**
	 * [$todayTimestamp 今天时间戳].
	 *
	 * @var [type]
	 */
	protected $todayTimestamp;

	protected $tomorrowDay;

	protected $tomorrowTimeStamp;

	/**
	 * [index 首页].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-03-07
	 *
	 * @version  1.0
	 *
	 * @param PlayerService $player [description]
	 * @param PayService    $pay    [description]
	 *
	 * @return Content
	 */
	public function index(PlayerService $player, PayService $pay) {
		$this->playService = $player;
		$this->pay = $pay;
		$yesterday = Carbon::yesterday();
		$today = Carbon::today();
		$tomorrow = Carbon::tomorrow();
		$this->tomorrowDay = $tomorrow->toDateString();
		$this->tomorrowTimeStamp = $tomorrow->timestamp;
		$this->yesterday = $yesterday->toDateString();
		$this->yesterdayTimestamp = $yesterday->timestamp;
		$this->today = $today->toDateString();
		$this->todayTimestamp = $today->timestamp;

		$str = <<<EOF
         $(".small-box-footer").css('display','none');
EOF;
		Admin::script($str);

		return Admin::content(function (Content $content) {
			$content->header(trans('game.home'));
			$content->description(trans('game.day_overview'));
			$this->rowPlayerView($content);
			$this->rowTableContent($content);
			$this->rowChartView($content);
		});
	}

	protected function rowTableContent($content) {
		$content->row(function (Row $row) use ($content) {
			$orders = OrderService::getTodayOrder(3);
			$headers = ['Id', trans('game.role_id'), trans('game.role_name'), trans('game.amount'), trans('game.server_name')];
			$table = new Table($headers, $orders);
			$amount = round($this->amount, 2);
			$order_num = OrderService::getTodayOrderNum();
			$more_url = route('orderTop.index');
			$dangri = trans('game.day_amount');
			$yuan = trans('game.yuan');
			$order_number = trans('game.order_number');
			$view_more = trans('game.view_more');
			$html = <<<EOF
            <div >
                <h4 class="text-center" style="display:inline" > $dangri ：$amount $yuan &nbsp;&nbsp;
                $order_number ：$order_num </h4>
                <a class="pull-right" href="$more_url">$view_more</a>
            </div>
EOF;
			$content->row((new Box(trans('game.pay_rank_day'), $html . $table))->style('info')->solid());
		});
	}

	/**
	 * [rowChartView 第二行图表].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-03-07
	 *
	 * @version  1.0
	 *
	 * @param [type] $content [description]
	 */
	protected function rowChartView($content) {
		$content->row(function (Row $row) {
			$row->column(6, function (Column $column) {
				//当日时段统计数据
				$online_data = $this->getHourNum();
				if ($online_data) {
					$hour_num = array_column($online_data, 'num');
					$hour = array_column($online_data, 'time');
				} else {
					$hour_num = $hour = [];
				}
				$column->append(view('admin.charts.login_timezone', ['hour_num' => $hour_num, 'hours' => $hour]));
			});

			$row->column(6, function (Column $column) {
				//近30天每日玩家数据
				$everyday_num = $this->getEverydayNum();
				if (!empty($everyday_num)) {
					$days = array_column($everyday_num, 'day');
					$numbers = array_column($everyday_num, 'numbers');
				} else {
					$days = $numbers = [];
				}
				$column->append(view('admin.charts.everyday_num', ['numbers' => $numbers, 'days' => $days]));
			});
		});
	}

	private function getEverydayNum() {
		$start_at = Carbon::parse('7 days ago')->toDateString();
		$end_at = Carbon::now()->toDateString();
		$data = StatEverdayPlayer::whereBetween('day', [$start_at, $end_at])
			->selectRaw('day,sum(number) as numbers')
			->groupBy('day')
			->get()->toArray();

		return $data ?: [];
	}

	/**
	 * [getHourNum 获取当日每小时玩家数量].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-04-21
	 *
	 * @version  1.0
	 *
	 * @return array|null
	 */
	private function getHourNum() {
		$nums = $nt = $hour_num = [];
		$data = PlayerService::todayOnlineTime();
		if ($data) {
			//时间转换为整型
			foreach ($data as $v) {
				$val['time'] = intval($v->hour);
				$val['num'] = $v->number;
				$nums[] = $val;
			}
			return array_sort($nums);
		} else {
			return null;
		}
	}

	/**
	 * [rowPlayerView 第一行数据渲染].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-03-07
	 *
	 * @version  1.0
	 *
	 * @param object $content
	 */
	protected function rowPlayerView($content) {
		$content->row(function (Row $row) {
			//在线玩家数量
			$player_online_num = $this->todayPlayerOnlineNum();
			//活跃用户
			$active_user_num = AccountService::todayActiveUser()->count();
			//新增玩家
			$new_player = PlayerService::NewPlayer();

			//新增玩家uid
			$uids = $new_player->pluck('ac_id')->all();

			//当日新增玩家数量
			$today_new_num = $new_player->count();

			//新增付费玩家数量
			$new_pay_num = PayService::getTodayPayNum($uids);

			//新玩家付费金额
			$new_user_orders = OrderService::getUserOrders($uids);
			if ($new_user_orders->isNotEmpty()) {
				$new_user_amount = $new_user_orders->pluck('amount')->sum();
			} else {
				$new_user_amount = 0;
			}

			//当日充值金额
			$this->amount = $this->todayAccount();

			//当日付费用户数量
			$today_pay_user_num = OrderService::payPlayerNum($this->todayTimestamp, $this->tomorrowTimeStamp);

			//新增arpu值
			$new_arpu = $today_new_num ? round($this->amount / $today_new_num, 2) : 0;
			//arpu值
			$arpu = $active_user_num ? round($this->amount / $active_user_num, 2) : 0;

			//付费arpu
			$pay_apru = $today_pay_user_num ? round($this->amount / $today_pay_user_num, 2) : 0;

			//玩家付费率
			$payRate = $active_user_num ? round($today_pay_user_num / $active_user_num, 4) * 100 . '%' : 0;

			$data = [
				['name' => trans('game.online_user_number').'：' . $player_online_num, 'icon' => 'users', 'color' => 'aqua', 'link' => '', 'info' => trans('game.new_reg').': ' . $today_new_num],
				['name' => trans('game.new_user_amount').': ' . $new_user_amount . '/'.trans('game.pay_user_number').'：' . $new_pay_num, 'icon' => 'users', 'color' => 'green', 'link' => '', 'info' => trans('game.active_user').'：' . $active_user_num],
				['name' => trans('game.day_pay_number').'：' . $today_pay_user_num, 'icon' => 'users', 'color' => 'yellow', 'link' => '', 'info' => trans('game.pay_rate').'：' . $payRate],
				['name' => trans('game.reg_arpu').'：' . $new_arpu . '/'.trans('game.pay_arpu').':' . $pay_apru, 'icon' => 'users', 'color' => 'red', 'link' => '', 'info' => trans('game.active_arpu').'：' . $arpu],
			];
			foreach ($data as $value) {
				$row->column(3, function (Column $column) use ($value) {
					$infoBox = new InfoBox($value['name'], $value['name'], $value['color'], $value['link'], $value['info']);
					$column->append($infoBox);
				});
			}
		});
	}

	/**
	 * [todayAccount 获取当日充值金额].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-03-07
	 *
	 * @version  1.0
	 *
	 * @return array
	 */
	public function todayAccount() {
		return $this->pay->getTodayAccount();
	}

	/**
	 * [TodayPlayerOnlineNum 玩家在线数量].
	 *
	 * @Author   王文凡
	 * @DateTime 2018-03-06
	 *
	 * @version  1.0
	 */
	protected function todayPlayerOnlineNum() {
		$list = ServerList::all();
		if (null == $list) {
			return false;
		}
		$online_num = 0;
		foreach ($list as $server) {
			//设置数据库配置
			setDB($server->server_id);
			$online_num += PlayerService::getOnlinePlayerNum();
		}

		return $online_num;
	}
}
